<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  {{ t('workplace.toady') }}，20℃ - 32℃！
                </div>
              </div>
            </div>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="h-70px flex items-center justify-end lt-sm:mt-10px">
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.project') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.project"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.toDo') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.todo"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" border-style="dashed" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.access') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.access"
                  :duration="2600"
                />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.project') }}</span>
            <div class="flex items-center gap-2">
              <el-button type="primary" size="small" @click="handleAddProject">
                <Icon icon="ep:plus" class="mr-1" />
                新增项目
              </el-button>
            </div>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col
              v-for="item in projects"
              :key="item.id"
              :xl="8"
              :lg="8"
              :md="8"
              :sm="24"
              :xs="24"
            >
              <el-card
                shadow="hover"
                class="mr-5px mt-5px cursor-pointer relative"
                :class="{ 'border-blue-500 bg-blue-50': selectedProject?.id === item.id }"
                @click.stop="handleProjectSelect(item)"
              >
                <!-- 操作按钮组 -->
                <div class="absolute top-2 right-2 z-10 flex gap-1">
                  <!-- 训练模型按钮 -->
                  <el-button
                    type="primary"
                    size="small"
                    circle
                    :loading="trainLoading[item.id]"
                    @click.stop="handleTrainModel(item)"
                    title="训练模型"
                  >
                    <Icon icon="ep:cpu" />
                  </el-button>
                  <!-- 删除按钮 -->
                  <el-button
                    type="danger"
                    size="small"
                    circle
                    @click.stop="handleDeleteProject(item)"
                  >
                    <Icon icon="ep:delete" />
                  </el-button>
                </div>

                <div class="flex items-center">
                  <Icon
                    :icon="item.icon"
                    :size="25"
                    class="mr-8px"
                    :style="{ color: item.color }"
                  />
                  <span class="text-16px">{{ item.name }}</span>
                </div>
                <div class="mt-12px text-12px text-gray-400">{{ item.message }}</div>
                <div class="mt-12px flex justify-between text-12px text-gray-400">
                  <span>{{ item.personal }}</span>
                  <span>{{ formatTime(item.time, 'yyyy-MM-dd') }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 分页组件 -->
          <div class="mt-4 flex justify-center">
            <el-pagination
              :current-page="projectPage.pageNo"
              :page-size="projectPage.pageSize"
              :page-sizes="[6, 12, 18, 24]"
              :total="projectTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleProjectSizeChange"
              @current-change="handleProjectPageChange"
            />
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between items-center">
            <span>分类内容</span>
            <div class="flex items-center gap-2">
              <span v-if="selectedProject" class="text-14px text-gray-500">
                项目：{{ selectedProject.name }}
              </span>
              <!-- 分类按钮组 -->
              <div class="flex items-center gap-1">
                <el-button
                  v-if="selectedProject"
                  :type="currentTypeFilter === 1 ? 'primary' : 'default'"
                  size="small"
                  @click="handleTypeFilter(1)"
                >
                  训练集
                </el-button>
                <el-button
                  v-if="selectedProject"
                  :type="currentTypeFilter === 2 ? 'primary' : 'default'"
                  size="small"
                  @click="handleTypeFilter(2)"
                >
                  测试集
                </el-button>
                <el-button
                  v-if="selectedProject"
                  :type="currentTypeFilter === null ? 'primary' : 'default'"
                  size="small"
                  @click="handleTypeFilter(null)"
                >
                  全部
                </el-button>
              </div>
              <el-button v-if="selectedProject" type="primary" size="small" @click="handleAddType">
                添加目录
              </el-button>
            </div>
          </div>
        </template>
        <el-skeleton :loading="folderLoading" animated>
          <div v-show="!selectedProject" class="text-center text-gray-500 py-20">
            请先选择一个项目查看分类内容
          </div>
          <div
            v-show="selectedProject && filteredFolderContents.length === 0"
            class="text-center text-gray-500 py-20"
          >
            {{
              currentTypeFilter === null
                ? '该项目暂无分类内容'
                : `该项目暂无${getTypeFilterText()}内容`
            }}
          </div>
          <div v-show="selectedProject && filteredFolderContents.length > 0" class="folder-content">
            <div v-for="item in filteredFolderContents" :key="item.id" class="folder-item">
              <div
                class="flex items-center p-3 hover:bg-gray-50 rounded border-b border-gray-100 relative group cursor-pointer"
                @click="handleFolderClick(item)"
              >
                <Icon
                  :icon="item.type === 1 ? 'ep:collection' : 'ep:finished'"
                  :class="item.type === 1 ? 'mr-3 text-green-500' : 'mr-3 text-orange-500'"
                />
                <div class="flex-1">
                  <div class="text-14px font-medium flex items-center gap-2">
                    <span>{{ item.name }}</span>
                    <el-tag size="small" :type="item.type === 1 ? 'success' : 'warning'">
                      {{ item.type === 1 ? '训练集' : '测试集' }}
                    </el-tag>
                  </div>
                  <div class="text-12px text-gray-500 mt-1">
                    {{ item.size }} • {{ formatTime(item.createTime, 'yyyy-MM-dd HH:mm') }}
                  </div>
                </div>
                <!-- 操作按钮组 -->
                <div
                  class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <!-- 路径按钮 -->
                  <el-button
                    type="info"
                    size="small"
                    circle
                    @click.stop="handleGetDirectoryPath(item)"
                  >
                    <Icon icon="ep:location" />
                  </el-button>
                  <!-- 上传按钮 -->
                  <el-button
                    type="primary"
                    size="small"
                    circle
                    :loading="uploadLoading"
                    @click.stop="handleUploadFiles(item)"
                  >
                    <Icon icon="ep:upload" />
                  </el-button>
                  <!-- 删除按钮 -->
                  <el-button
                    type="danger"
                    size="small"
                    circle
                    @click.stop="handleDeleteDirectory(item)"
                  >
                    <Icon icon="ep:delete" />
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>

  <!-- 模型列表展示区域 -->
  <el-row class="mt-8px" :gutter="8" v-show="!!selectedProject">
    <el-col :span="24">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between items-center">
            <span>模型列表</span>
            <div class="flex items-center gap-2">
              <span class="text-14px text-gray-500"> 项目：{{ selectedProject?.name ?? '' }} </span>
            </div>
          </div>
        </template>
        <el-skeleton :loading="modelLoading" animated>
          <div v-if="modelList.length === 0" class="text-center text-gray-500 py-20">
            该项目暂无模型数据
          </div>
          <div v-else class="model-content">
            <div v-for="model in modelList" :key="model.id" class="model-item">
              <div
                class="flex items-center p-3 hover:bg-gray-50 rounded border-b border-gray-100 cursor-pointer"
                @click="handleModelClick(model)"
              >
                <!-- 状态图标 -->
                <Icon
                  :icon="getModelStatusInfo(model.status).icon"
                  class="mr-3"
                  :style="{ color: getModelStatusInfo(model.status).color }"
                  :class="{ 'animate-spin': model.status === ModelStatus.TRAINING }"
                />
                <div class="flex-1">
                  <div class="text-14px font-medium flex items-center gap-2">
                    <span>{{ model.modeName }}</span>
                    <!-- 状态标签 -->
                    <el-tag :type="getModelStatusInfo(model.status).type" size="small">
                      {{ getModelStatusInfo(model.status).text }}
                    </el-tag>
                    <!-- 准确率标签 -->
                    <el-tag
                      v-if="
                        model.status === ModelStatus.COMPLETED &&
                        model.accuracy !== null &&
                        model.accuracy !== undefined
                      "
                      type="primary"
                      size="small"
                    >
                      {{ formatAccuracy(model.accuracy) }}
                    </el-tag>
                  </div>
                  <div class="text-12px text-gray-500 mt-1">
                    父类模型：{{ model.modeParents || '无' }} • 路径：{{ model.modePath }}
                  </div>
                </div>
                <div class="flex items-center gap-1">
                  <el-button
                    type="primary"
                    size="small"
                    circle
                    @click.stop="handleModelClick(model)"
                  >
                    <Icon icon="ep:view" />
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    circle
                    @click.stop="handleDeleteModel(model)"
                  >
                    <Icon icon="ep:delete" />
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 模型分页组件 -->
          <div class="mt-4 flex justify-center" v-if="modelTotal > 0">
            <el-pagination
              :current-page="modelPage.pageNo"
              :page-size="modelPage.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :total="modelTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleModelSizeChange"
              @current-change="handleModelPageChange"
            />
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>

  <!-- 项目表单弹窗 -->
  <OxProjectForm ref="projectFormRef" @success="handleProjectSuccess" />

  <!-- 隐藏的文件上传input -->
  <input
    ref="fileInputRef"
    type="file"
    multiple
    accept="image/*"
    style="display: none"
    @change="handleFileSelect"
  />

  <!-- 添加目录弹框 -->
  <el-dialog
    v-model="directoryDialogVisible"
    title="添加目录"
    width="400px"
    :before-close="handleDirectoryDialogClose"
  >
    <el-form
      ref="directoryFormRef"
      :model="directoryForm"
      :rules="directoryRules"
      label-width="80px"
    >
      <el-form-item label="目录名称" prop="name">
        <el-input v-model="directoryForm.name" placeholder="请输入目录名称" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDirectoryDialogClose">取消</el-button>
        <el-button type="primary" @click="handleAddTypeSubmit" :loading="directoryLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 目录路径弹框 -->
  <el-dialog
    v-model="pathDialogVisible"
    title="目录路径"
    width="500px"
    :before-close="handlePathDialogClose"
  >
    <div class="path-content">
      <div class="mb-3">
        <span class="text-gray-600">目录：</span>
        <span class="font-medium">{{ currentPathDirectory?.name }}</span>
      </div>
      <div class="mb-3">
        <span class="text-gray-600">路径：</span>
      </div>
      <div class="path-display">
        <el-input
          v-model="directoryPath"
          readonly
          type="textarea"
          :rows="3"
          :placeholder="pathLoading ? '正在获取路径...' : '暂无路径信息'"
          class="mb-3"
          :loading="pathLoading"
        />
        <div class="flex justify-end">
          <el-button type="primary" @click="handleCopyPath" :disabled="!directoryPath">
            <Icon icon="ep:copy-document" class="mr-1" />
            复制路径
          </el-button>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlePathDialogClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 模型上传图片弹框 -->
  <el-dialog
    v-model="modelUploadDialogVisible"
    title="上传图片进行预测"
    width="600px"
    :before-close="handleModelUploadDialogClose"
  >
    <div class="model-upload-content">
      <div class="mb-4">
        <span class="text-gray-600">模型：</span>
        <span class="font-medium">{{ currentModel?.modeName }}</span>
      </div>
      <div class="mb-4">
        <span class="text-gray-600 mb-2 block">上传图片：</span>
        <UploadImg v-model="modelUploadImageUrl" height="200px" width="100%" :file-size="10" />
      </div>
      <div v-if="modelPredictResult" class="mt-4">
        <el-divider>预测结果</el-divider>
        <div class="predict-result">
          <div v-if="modelPredictResult.success" class="success-result">
            <div class="flex items-center mb-3">
              <el-icon class="text-green-500 mr-2" :size="20">
                <Icon icon="ep:check" />
              </el-icon>
              <span class="text-16px font-bold text-green-600">预测成功</span>
            </div>
            <div v-if="modelPredictResult.data" class="ml-6">
              <p class="text-16px font-bold mb-2">标签: {{ modelPredictResult.data.label }}</p>
              <p v-if="modelPredictResult.data.confidence" class="text-14px text-gray-600">
                置信度: {{ modelPredictResult.data.confidence }}
              </p>
            </div>
          </div>
          <div v-else class="error-result">
            <div class="flex items-center">
              <el-icon class="text-red-500 mr-2" :size="20">
                <Icon icon="ep:close" />
              </el-icon>
              <span class="text-16px font-bold text-red-600">{{ modelPredictResult.message }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleModelUploadDialogClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleModelPredict"
          :loading="modelPredictLoading"
          :disabled="!modelUploadImageUrl"
        >
          开始预测
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { formatTime } from '@/utils'
import { OxProjectApi } from '@/api/happy-ox-core/oxproject'
import { OxDirectoryApi } from '@/api/happy-ox-core/oxdirectory'
import { OxModeApi, OxMode } from '@/api/happy-ox-core/oxmode'
import { useUserStore } from '@/store/modules/user'
import { UploadImg } from '@/components/UploadFile'
// import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project } from './types'
import OxProjectForm from '@/views/happy-ox-core/oxproject/OxProjectForm.vue'

defineOptions({ name: 'Index' })

// 模型状态枚举
enum ModelStatus {
  TRAINING = 0, // 训练中
  COMPLETED = 1, // 已完成
  FAILED = 2 // 失败
}

// 模型状态映射
const getModelStatusInfo = (status: number) => {
  switch (status) {
    case ModelStatus.TRAINING:
      return {
        text: '训练中',
        type: 'warning' as const,
        icon: 'ep:loading',
        color: '#E6A23C'
      }
    case ModelStatus.COMPLETED:
      return {
        text: '已完成',
        type: 'success' as const,
        icon: 'ep:check',
        color: '#67C23A'
      }
    case ModelStatus.FAILED:
      return {
        text: '失败',
        type: 'danger' as const,
        icon: 'ep:close',
        color: '#F56C6C'
      }
    default:
      return {
        text: '未知',
        type: 'info' as const,
        icon: 'ep:question-filled',
        color: '#909399'
      }
  }
}

// 准确率原样显示（支持字符串或数字）
const formatAccuracy = (accuracy: string | number) => {
  if (accuracy === null || accuracy === undefined) {
    return '--'
  }
  return String(accuracy)
}

const { t } = useI18n()
const message = useMessage()
const userStore = useUserStore()

// 导入 ElMessageBox
import { ElMessageBox } from 'element-plus'
// const { setWatermark } = useWatermark()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  // 项目总数会在 getProject 中更新，这里只需要设置其他统计
  const data = {
    project: projectTotal.value,
    access: 2340, // 访问量可以保持固定或从其他API获取
    todo: 10 // 待办事项可以保持固定或从其他API获取
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])

// 项目分页相关
const projectPage = reactive({
  pageNo: 1,
  pageSize: 6
})
const projectTotal = ref(0)

// 选中的项目和文件夹内容
const selectedProject = ref<Project | null>(null)
const folderContents = ref<any[]>([])
const folderLoading = ref(false)
const lastSelectedProjectId = ref<number | null>(null)

// 模型列表相关
const modelList = ref<OxMode[]>([])
const modelLoading = ref(false)
const modelPage = reactive({
  pageNo: 1,
  pageSize: 10
})
const modelTotal = ref(0)
const getProject = async () => {
  try {
    console.log('获取项目列表，分页参数:', projectPage)
    const response = await OxProjectApi.getOxProjectPage(projectPage)
    console.log('API响应:', response)

    // 处理API响应数据
    if (response && response.list) {
      // 更新总数
      projectTotal.value = response.total || 0

      // 更新统计信息
      totalSate.project = projectTotal.value

      // 清空之前的项目数据
      projects.splice(0, projects.length)

      const projectList = response.list.map((item: any, index: number) => {
        // 定义项目图标和颜色的映射
        const projectConfigs = [
          { icon: 'simple-icons:springboot', color: '#6DB33F' },
          { icon: 'ep:element-plus', color: '#409EFF' },
          { icon: 'icon-park-outline:mall-bag', color: '#ff4d4f' },
          { icon: 'material-symbols:cloud-outline', color: '#1890ff' },
          { icon: 'devicon:antdesign', color: '#e18525' },
          { icon: 'ant-design:mobile', color: '#2979ff' }
        ]

        const config = projectConfigs[index % projectConfigs.length]

        return {
          id: item.id,
          name: item.projectName,
          icon: config.icon,
          message: item.projectPath,
          personal: item.remark || '项目描述',
          time: item.createTime ? new Date(item.createTime) : new Date(),
          color: config.color
        }
      })

      // 将新数据添加到项目中
      projectList.forEach((item) => {
        projects.push(item)
      })

      console.log('更新后的项目列表:', projects)
      console.log('项目列表长度:', projects.length)
    }
  } catch (error) {
    // 如果API调用失败，显示默认项目
    const defaultProjects = [
      {
        id: 1,
        name: '默认项目',
        icon: 'simple-icons:springboot',
        message: '暂无项目数据',
        personal: '请先创建项目',
        time: new Date(),
        color: '#6DB33F'
      }
    ]
    projects = Object.assign(projects, defaultProjects)
  }
}

const getAllApi = async () => {
  await Promise.all([getCount(), getProject()])
  loading.value = false
}

// 项目选择处理函数
const handleProjectSelect = async (project: Project, forceRefresh = false) => {
  console.log('项目选择函数被调用:', project)

  // 防止重复调用
  if (folderLoading.value || modelLoading.value) {
    console.log('正在加载中，跳过重复调用')
    return
  }

  // 防止选择同一个项目（除非强制刷新）
  if (lastSelectedProjectId.value === project.id && !forceRefresh) {
    console.log('选择相同项目，跳过')
    return
  }

  console.log('开始加载项目数据:', project.name)
  selectedProject.value = project
  lastSelectedProjectId.value = project.id
  folderLoading.value = true
  modelLoading.value = true

  // 重置类型过滤
  currentTypeFilter.value = null

  try {
    // 并行获取目录和模型数据
    const [directoryResponse, modelResponse] = await Promise.all([
      OxDirectoryApi.selectByProjectId(project.id),
      OxModeApi.getOxModePage({
        projectId: project.id,
        pageNo: modelPage.pageNo,
        pageSize: modelPage.pageSize
      })
    ])

    console.log('directory response', directoryResponse)
    console.log('model response', modelResponse)

    // 处理目录数据
    if (directoryResponse && Array.isArray(directoryResponse)) {
      folderContents.value = directoryResponse.map((item: any) => ({
        name: item.directoryName || '未知目录',
        type: item.type,
        size: item.imagesNum > 0 ? `${item.imagesNum} 张图片` : '空目录',
        id: item.id,
        projectId: item.projectId,
        createTime: item.createTime
      }))
    } else {
      folderContents.value = []
    }

    // 处理模型数据（兼容后端返回 { code, msg, data: { list, total } } 或直接 { list, total }）
    const mr = modelResponse as any
    const md = mr?.data ?? mr
    if (md && Array.isArray(md.list)) {
      modelList.value = md.list
      modelTotal.value = md.total || 0
      console.log('模型数据加载成功:', modelList.value)
      console.log('模型总数:', modelTotal.value)
      console.log('第一个模型数据:', md.list[0])
    } else {
      modelList.value = []
      modelTotal.value = 0
      console.log('模型数据为空或格式错误:', modelResponse)
    }
  } catch (error) {
    folderContents.value = []
    modelList.value = []
    modelTotal.value = 0
    message.error('获取项目数据失败，请稍后重试')
  } finally {
    folderLoading.value = false
    modelLoading.value = false
  }
}

// 项目表单引用
const projectFormRef = ref()

// 目录弹框相关
const directoryDialogVisible = ref(false)
const directoryFormRef = ref()
const directoryLoading = ref(false)
const directoryForm = reactive({
  name: ''
})
const directoryRules = {
  name: [
    { required: true, message: '请输入目录名称', trigger: 'blur' },
    { min: 1, max: 50, message: '目录名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 文件上传相关
const fileInputRef = ref()
const currentDirectory = ref<any>(null)
const uploadLoading = ref(false)

// 训练模型相关
const trainLoading = ref<Record<number, boolean>>({})

// 路径弹框相关
const pathDialogVisible = ref(false)
const currentPathDirectory = ref<any>(null)
const directoryPath = ref('')
const pathLoading = ref(false)

// 类型过滤相关
const currentTypeFilter = ref<number | null>(null)
const filteredFolderContents = computed(() => {
  if (currentTypeFilter.value === null) {
    return folderContents.value
  }
  return folderContents.value.filter((item) => item.type === currentTypeFilter.value)
})

// 新增项目按钮点击事件
const handleAddProject = () => {
  projectFormRef.value?.open('create')
}

// 项目创建成功后的回调
const handleProjectSuccess = () => {
  // 重新获取项目列表
  getProject()
}

// 分页大小改变
const handleProjectSizeChange = (size: number) => {
  console.log('分页大小改变:', size)
  projectPage.pageSize = size
  projectPage.pageNo = 1 // 重置到第一页
  console.log('新的分页参数:', projectPage)
  getProject()
}

// 页码改变
const handleProjectPageChange = (page: number) => {
  console.log('页码改变:', page)
  projectPage.pageNo = page
  console.log('新的分页参数:', projectPage)
  getProject()
}

// 模型分页大小改变
const handleModelSizeChange = (size: number) => {
  console.log('模型分页大小改变:', size)
  modelPage.pageSize = size
  modelPage.pageNo = 1 // 重置到第一页
  if (selectedProject.value) {
    handleProjectSelect(selectedProject.value, true)
  }
}

// 模型页码改变
const handleModelPageChange = (page: number) => {
  console.log('模型页码改变:', page)
  modelPage.pageNo = page
  if (selectedProject.value) {
    handleProjectSelect(selectedProject.value, true)
  }
}

// 删除项目
const handleDeleteProject = async (project: Project) => {
  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(`确定要删除项目 "${project.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    })

    // 用户确认删除
    console.log('删除项目:', project.name, 'ID:', project.id)

    // 调用删除API
    await OxProjectApi.deleteOxProject(project.id)

    // 删除成功提示
    message.success('项目删除成功')

    // 如果删除的是当前选中的项目，清空选中状态
    if (selectedProject.value?.id === project.id) {
      selectedProject.value = null
      folderContents.value = []
    }

    // 重新获取项目列表
    getProject()
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      console.log('用户取消删除')
    } else {
      // 删除失败
      console.error('删除项目失败:', error)
      message.error('删除项目失败，请稍后重试')
    }
  }
}

// 添加目录按钮点击事件
const handleAddType = () => {
  if (!selectedProject.value) {
    message.warning('请先选择一个项目')
    return
  }
  directoryDialogVisible.value = true
}

// 目录弹框关闭
const handleDirectoryDialogClose = () => {
  directoryDialogVisible.value = false
  directoryForm.name = ''
  directoryFormRef.value?.resetFields()
}

// 目录表单提交
const handleAddTypeSubmit = async () => {
  if (!directoryFormRef.value) return

  try {
    // 表单验证
    await directoryFormRef.value.validate()

    directoryLoading.value = true

    // 调用添加目录API
    await OxDirectoryApi.addType({
      projectId: selectedProject.value!.id,
      name: directoryForm.name
    })

    // 添加成功
    message.success('目录添加成功')

    // 关闭弹框
    handleDirectoryDialogClose()

    // 重新获取文件夹内容（强制刷新）
    if (selectedProject.value) {
      await handleProjectSelect(selectedProject.value, true)
    }
  } catch (error) {
    console.error('添加目录失败:', error)
    message.error('添加目录失败，请稍后重试')
  } finally {
    directoryLoading.value = false
  }
}

// 文件夹点击事件
const handleFolderClick = (directory: any) => {
  console.log('点击文件夹:', directory.name)
  // 这里可以添加其他文件夹点击逻辑，比如查看文件夹内容等
}

// 上传文件按钮点击
const handleUploadFiles = (directory: any) => {
  currentDirectory.value = directory
  fileInputRef.value?.click()
}

// 文件选择处理
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (!files || files.length === 0) {
    return
  }

  if (!currentDirectory.value) {
    message.error('请先选择目录')
    return
  }

  // 验证文件类型
  const imageFiles = Array.from(files).filter((file) => file.type.startsWith('image/'))
  if (imageFiles.length === 0) {
    message.error('请选择图片文件')
    return
  }

  if (imageFiles.length !== files.length) {
    message.warning(`已过滤掉 ${files.length - imageFiles.length} 个非图片文件`)
  }

  try {
    uploadLoading.value = true

    // 调用上传API
    await OxDirectoryApi.uploadFilesToDirectory(currentDirectory.value.id, imageFiles)

    message.success(`成功上传 ${imageFiles.length} 个文件`)

    // 重新获取文件夹内容
    if (selectedProject.value) {
      await handleProjectSelect(selectedProject.value, true)
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    message.error('文件上传失败，请稍后重试')
  } finally {
    uploadLoading.value = false
    // 清空文件输入
    target.value = ''
  }
}

// 获取目录路径
const handleGetDirectoryPath = async (directory: any) => {
  try {
    currentPathDirectory.value = directory
    pathDialogVisible.value = true
    directoryPath.value = ''
    pathLoading.value = true

    // 调用获取路径API
    const response = await OxDirectoryApi.getDirectoryPath(directory.id)

    // 处理API响应
    if (response && response.data) {
      directoryPath.value = response.data
    } else if (response && typeof response === 'string') {
      directoryPath.value = response
    } else {
      directoryPath.value = '路径获取失败'
    }
  } catch (error) {
    console.error('获取目录路径失败:', error)
    directoryPath.value = '路径获取失败'
    message.error('获取目录路径失败，请稍后重试')
  } finally {
    pathLoading.value = false
  }
}

// 复制路径
const handleCopyPath = async () => {
  try {
    await navigator.clipboard.writeText(directoryPath.value)
    message.success('路径已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    // 降级方案：使用传统方法复制
    const textArea = document.createElement('textarea')
    textArea.value = directoryPath.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    message.success('路径已复制到剪贴板')
  }
}

// 路径弹框关闭
const handlePathDialogClose = () => {
  pathDialogVisible.value = false
  currentPathDirectory.value = null
  directoryPath.value = ''
}

// 类型过滤处理
const handleTypeFilter = (type: number | null) => {
  currentTypeFilter.value = type
  console.log('切换类型过滤:', type === null ? '全部' : type === 1 ? '训练集' : '测试集')
}

// 获取类型过滤文本
const getTypeFilterText = () => {
  if (currentTypeFilter.value === 1) return '训练集'
  if (currentTypeFilter.value === 2) return '测试集'
  return '分类'
}

// 删除目录
const handleDeleteDirectory = async (directory: any) => {
  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(`确定要删除目录 "${directory.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    })

    // 用户确认删除
    console.log('删除目录:', directory.name, 'ID:', directory.id)

    // 调用删除API
    await OxDirectoryApi.deleteOxDirectory(directory.id)

    // 删除成功提示
    message.success('目录删除成功')

    // 重新获取文件夹内容（强制刷新）
    if (selectedProject.value) {
      await handleProjectSelect(selectedProject.value, true)
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      console.log('用户取消删除目录')
    } else {
      // 删除失败
      console.error('删除目录失败:', error)
      message.error('删除目录失败，请稍后重试')
    }
  }
}

// 训练模型
const handleTrainModel = async (project: Project) => {
  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(
      `确定要开始训练项目 "${project.name}" 的模型吗？训练过程可能需要较长时间。`,
      '训练确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 设置加载状态
    trainLoading.value[project.id] = true

    // 调用训练模型API
    await OxProjectApi.trainModel(project.id)

    // 训练成功提示
    message.success('模型训练已开始，请耐心等待训练完成')

    console.log('开始训练项目模型:', project.name, 'ID:', project.id)
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消训练
      console.log('用户取消训练模型')
    } else {
      // 训练失败
      console.error('训练模型失败:', error)
      message.error('训练模型失败，请稍后重试')
    }
  } finally {
    // 清除加载状态
    trainLoading.value[project.id] = false
  }
}

// 模型上传弹框相关
const modelUploadDialogVisible = ref(false)
const currentModel = ref<OxMode | null>(null)
const modelUploadImageUrl = ref('')
const modelPredictLoading = ref(false)
const modelPredictResult = ref<any>(null)

// 模型点击事件
const handleModelClick = (model: OxMode) => {
  // 检查模型状态，只有已完成的模型才能进行预测
  if (model.status !== ModelStatus.COMPLETED) {
    message.warning('只有已完成的模型才能进行预测')
    return
  }
  currentModel.value = model
  modelUploadImageUrl.value = ''
  modelPredictResult.value = null
  modelUploadDialogVisible.value = true
}

// 模型上传弹框关闭
const handleModelUploadDialogClose = () => {
  modelUploadDialogVisible.value = false
  currentModel.value = null
  modelUploadImageUrl.value = ''
  modelPredictResult.value = null
}

// 模型预测
const handleModelPredict = async () => {
  if (!currentModel.value || !modelUploadImageUrl.value) {
    message.warning('请先上传图片')
    return
  }

  try {
    modelPredictLoading.value = true

    // 调用预测API
    const response = await OxModeApi.predictDog({
      modelId: currentModel.value.id,
      imagePath: modelUploadImageUrl.value
    })

    // 处理预测结果
    if (response) {
      // 判断返回的数据类型
      let predictData: any = null

      if (typeof response === 'string') {
        // 如果是字符串，直接作为标签
        predictData = {
          label: response,
          confidence: null
        }
      } else if (typeof response === 'object' && response !== null) {
        // 如果是对象，使用对象数据
        predictData = response
      }

      modelPredictResult.value = {
        success: true,
        message: '预测成功',
        data: predictData
      }
    } else {
      modelPredictResult.value = {
        success: false,
        message: response?.msg || '预测失败'
      }
    }
  } catch (error) {
    console.error('预测失败:', error)
    modelPredictResult.value = {
      success: false,
      message: '预测失败，请稍后重试'
    }
  } finally {
    modelPredictLoading.value = false
  }
}

// 删除模型
const handleDeleteModel = async (model: OxMode) => {
  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(`确定要删除模型 "${model.modeName}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    })

    // 用户确认删除
    console.log('删除模型:', model.modeName, 'ID:', model.id)

    // 调用删除API
    await OxModeApi.deleteOxMode(model.id)

    // 删除成功提示
    message.success('模型删除成功')

    // 重新获取模型列表（强制刷新）
    if (selectedProject.value) {
      await handleProjectSelect(selectedProject.value, true)
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      console.log('用户取消删除模型')
    } else {
      // 删除失败
      console.error('删除模型失败:', error)
      message.error('删除模型失败，请稍后重试')
    }
  }
}

getAllApi()
</script>
